import React, { useState } from 'react'
import { Tag, Layout, Button, Popconfirm, DatePicker, message } from 'antd'

import { connect } from 'react-redux'
import { changeLuckySheetOption, changeUnFillUser, changeUpdateDate, changeMonthTitle } from '../../redux/actionCreator/lineLossFillActionCreater'
import moment from 'moment'
import { logout } from '../../utils/auth/AuthUtils'
import { useNavigate } from 'react-router-dom'
import axios from 'axios'
import CheckUnFill from './CheckUnFill'


// 页头
const { Header } = Layout

// 页头功能按钮
function FillHeader (props) {

  const { updateDate, changeUnFillUser, month, changeLuckySheetOption, changeMonthTitle, changeUpdateDate } = props
  const defaultOption = {
    container: "luckysheet",
    lang: 'zh',
    showinfobar: false
  }

  // 内部状态控制按钮的加载状态
  const [loading, setLoading] = useState(false)






  // 获取填报时间
  const getInsertTime = async (month) => {
    await axios.get("http://localhost:8081/system/lineLossFill/getFillDate",
      {
        params: {
          username: localStorage.getItem("username"),
          month: month
        },
        headers: {
          satoken: localStorage.getItem("satoken")
        }
      }
    ).then(r => {
      if (r.data.code === 200) {
        changeUpdateDate(r.data.data)
      } else {
        changeUpdateDate("")
      }
    })
  }

  // 下载当前页面的excel
  const downloadExcel = async () => {

    // 使按钮变成加载状态，防止重复请求
    setLoading(true)
    await axios({
      url: "http://localhost:8081/system/lineLossFill/downloadExcel",
      method: "post",
      data: {
        excelOption: JSON.stringify(window.luckysheet.getAllSheets())
      },
      headers: {
        'satoken': localStorage.getItem("satoken")
      },
      responseType: 'blob'
    }
    ).then(r => {
      // 关闭加载状态
      setLoading(false)
      if (r.status === 200) {
        //console.log(r.headers)
        const fileName = moment().format('YYYY-MM') + "月" + decodeURI(r.headers['filename'])
        const blob = new Blob([r.data], { type: r.headers['content-type'] })
        //创建一个超链接，将文件流赋进去，然后实现这个超链接的单击事件
        const eLink = document.createElement('a')
        eLink.download = fileName
        eLink.style.display = 'none'
        eLink.href = URL.createObjectURL(blob)
        document.body.appendChild(eLink)
        eLink.click()
        URL.revokeObjectURL(eLink.href) // 释放URL 对象
        document.body.removeChild(eLink)
      } else {
        return message.err("下载失败")
      }
    })
  }
  //日期的点击事件
  const onChange = async (date, dateString) => {
    // 是否为模板
    changeMonthTitle(dateString)
    getInsertTime(dateString)
    await axios.post(
      "http://localhost:8081/system/lineLossFill/getReport",
      {
        username: localStorage.getItem("username"),
        date: dateString
      },
      {
        Pragma: 'no-cache',
        headers: { 'satoken': localStorage.getItem("satoken") }
      }
    ).then(r => {
      if (r.status === 200) {
        console.log(r.data)
        defaultOption.data = r.data
        changeLuckySheetOption(JSON.stringify(defaultOption))
        changeUnFillUser([])
      }
    })
  }

  // 编程式跳转
  const navigate = useNavigate()

  //提交按钮
  const commitData = async (commitMonth) => {
    await axios.post("http://localhost:8081/system/lineLossFill/updateFillTemp",
      {
        username: localStorage.getItem("username"),
        insertDate: commitMonth,
        fillConfig: JSON.stringify(window.luckysheet.getAllSheets()),
        // 提交的具体时间
        insertTime: moment().format('YYYY-MM-DD HH:mm:ss')
      },
      {
        headers: { 'satoken': localStorage.getItem("satoken") }
      }).then(r => {
        if (r.data.code === 200) {
          changeUpdateDate(moment().format('YYYY-MM-DD HH:mm:ss'))
          //return message.success(r.data.msg)
        } else {
          navigate("/login")
        }
      })
  }


  return (
    <>
      <Header
        className='temp-header'
        style={{ width: '100%' }}
      >
        <span
          className='tempHeaderTitle'
        >网损月报填报</span>

        <Popconfirm
          title="确认注销?"
          onConfirm={() => {
            logout()
            navigate('/login')
          }}
          onCancel={() => { }}
          okText="退出"
          cancelText="取消"
        >
          <Button
            danger
            className='tempHeaderBtn'
            ghost
          >注销 </Button>
        </Popconfirm>
        {/* 华东的功能 */}
        {localStorage.getItem("username") === "hd" ? <CheckUnFill></CheckUnFill> : ""}
        {/* 华东用户是下载功能 */}
        {localStorage.getItem("username") === "hd" ?
          <Button
            className='tempHeaderBtn'
            type="primary"
            ghost
            loading={loading}
            onClick={() => { downloadExcel() }}>下载</Button> :

          <Button
            className='tempHeaderBtn'
            type="primary"
            ghost
            onClick={() => {
              if (month === "" || month === moment().format('YYYY-MM')) {
                commitData(moment().format('YYYY-MM'))
              } else {
                commitData(month)
              }
            }}
          >提交</Button>}


        {
          localStorage.getItem("username") === "hd" ? "" :
            (updateDate === "" ? "" : <Tag
              className='headerInfoTag'
              color="magenta">{"最后一次提交于：" + updateDate}</Tag>)}
        {/*日历  */}
        <DatePicker key='7' className='date-picker' onChange={onChange} picker="month" />

        {/* 华东用户不用提醒是否提交 */}
        <div className='fillInfo'>{localStorage.getItem("username") === "hd" ? "" : (updateDate === "" ? month + "未填报，此为模板" : "")}</div>
      </Header>
    </>
  )
}

// 获取公共状态
const mapStateToProps = (state) => {
  return {
    updateDate: state.LineLossFillReducer.updateDate,
    month: state.LineLossFillReducer.month
  }
}

// 修改公共状态的方法
const mapDispatchToProps = {
  changeLuckySheetOption,
  changeUpdateDate,
  changeMonthTitle,
  changeUnFillUser
}

export default connect(mapStateToProps, mapDispatchToProps)(FillHeader)